import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { AdminStats, User, Plugin, AuditLog, SecurityScan, UserFilters, PluginFilters } from '@/types/api'
import { adminService } from '@/services/api/adminService'

interface AdminState {
  // Dashboard
  stats: AdminStats | null
  
  // User management
  users: User[]
  pendingUsers: User[]
  
  // Plugin management
  pendingPlugins: Plugin[]
  allPlugins: Plugin[]
  
  // Security
  securityScans: SecurityScan[]
  securityStats: any
  
  // Audit logs
  auditLogs: AuditLog[]
  
  // UI state
  isLoading: boolean
  isLoadingStats: boolean
  isLoadingUsers: boolean
  isLoadingPlugins: boolean
  isLoadingSecurity: boolean
  error: string | null
}

const initialState: AdminState = {
  stats: null,
  users: [],
  pendingUsers: [],
  pendingPlugins: [],
  allPlugins: [],
  securityScans: [],
  securityStats: null,
  auditLogs: [],
  isLoading: false,
  isLoadingStats: false,
  isLoadingUsers: false,
  isLoadingPlugins: false,
  isLoadingSecurity: false,
  error: null,
}

// Async thunks
export const fetchAdminStats = createAsyncThunk(
  'admin/fetchStats',
  async (_, { rejectWithValue }) => {
    try {
      const response = await adminService.getStats()
      return response.data
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.error?.message || 'Failed to fetch stats')
    }
  }
)

export const fetchUsers = createAsyncThunk(
  'admin/fetchUsers',
  async (filters: UserFilters, { rejectWithValue }) => {
    try {
      const response = await adminService.getUsers(filters)
      return response.data
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.error?.message || 'Failed to fetch users')
    }
  }
)

export const fetchPendingPlugins = createAsyncThunk(
  'admin/fetchPendingPlugins',
  async (_, { rejectWithValue }) => {
    try {
      const response = await adminService.getPendingPlugins()
      return response.data
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.error?.message || 'Failed to fetch pending plugins')
    }
  }
)

export const fetchAllPlugins = createAsyncThunk(
  'admin/fetchAllPlugins',
  async (filters: PluginFilters, { rejectWithValue }) => {
    try {
      const response = await adminService.getAllPlugins(filters)
      return response.data
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.error?.message || 'Failed to fetch plugins')
    }
  }
)

export const approvePlugin = createAsyncThunk(
  'admin/approvePlugin',
  async ({ id, reason }: { id: string; reason?: string }, { rejectWithValue }) => {
    try {
      const response = await adminService.approvePlugin(id, reason)
      return { id, ...response.data }
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.error?.message || 'Failed to approve plugin')
    }
  }
)

export const rejectPlugin = createAsyncThunk(
  'admin/rejectPlugin',
  async ({ id, reason }: { id: string; reason: string }, { rejectWithValue }) => {
    try {
      const response = await adminService.rejectPlugin(id, reason)
      return { id, ...response.data }
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.error?.message || 'Failed to reject plugin')
    }
  }
)

export const suspendPlugin = createAsyncThunk(
  'admin/suspendPlugin',
  async ({ id, reason }: { id: string; reason: string }, { rejectWithValue }) => {
    try {
      const response = await adminService.suspendPlugin(id, reason)
      return { id, ...response.data }
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.error?.message || 'Failed to suspend plugin')
    }
  }
)

export const suspendUser = createAsyncThunk(
  'admin/suspendUser',
  async ({ id, reason }: { id: string; reason: string }, { rejectWithValue }) => {
    try {
      const response = await adminService.suspendUser(id, reason)
      return { id, ...response.data }
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.error?.message || 'Failed to suspend user')
    }
  }
)

export const fetchAuditLogs = createAsyncThunk(
  'admin/fetchAuditLogs',
  async (filters: any, { rejectWithValue }) => {
    try {
      const response = await adminService.getAuditLogs(filters)
      return response.data
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.error?.message || 'Failed to fetch audit logs')
    }
  }
)

export const fetchSecurityStats = createAsyncThunk(
  'admin/fetchSecurityStats',
  async (_, { rejectWithValue }) => {
    try {
      const response = await adminService.getSecurityStats()
      return response.data
    } catch (error: any) {
      return rejectWithValue(error.response?.data?.error?.message || 'Failed to fetch security stats')
    }
  }
)

export const adminSlice = createSlice({
  name: 'admin',
  initialState,
  reducers: {
    clearError: (state) => {
      state.error = null
    },
  },
  extraReducers: (builder) => {
    // Fetch admin stats
    builder
      .addCase(fetchAdminStats.pending, (state) => {
        state.isLoadingStats = true
        state.error = null
      })
      .addCase(fetchAdminStats.fulfilled, (state, action) => {
        state.isLoadingStats = false
        if (action.payload) {
          state.stats = action.payload
        }
      })
      .addCase(fetchAdminStats.rejected, (state, action) => {
        state.isLoadingStats = false
        state.error = action.payload as string
      })

    // Fetch users
    builder
      .addCase(fetchUsers.pending, (state) => {
        state.isLoadingUsers = true
      })
      .addCase(fetchUsers.fulfilled, (state, action) => {
        state.isLoadingUsers = false
        if (action.payload) {
          state.users = action.payload.users
        }
      })
      .addCase(fetchUsers.rejected, (state, action) => {
        state.isLoadingUsers = false
        state.error = action.payload as string
      })

    // Fetch pending plugins
    builder
      .addCase(fetchPendingPlugins.pending, (state) => {
        state.isLoadingPlugins = true
      })
      .addCase(fetchPendingPlugins.fulfilled, (state, action) => {
        state.isLoadingPlugins = false
        if (action.payload) {
          state.pendingPlugins = action.payload.plugins
        }
      })
      .addCase(fetchPendingPlugins.rejected, (state, action) => {
        state.isLoadingPlugins = false
        state.error = action.payload as string
      })

    // Fetch all plugins
    builder
      .addCase(fetchAllPlugins.pending, (state) => {
        state.isLoadingPlugins = true
      })
      .addCase(fetchAllPlugins.fulfilled, (state, action) => {
        state.isLoadingPlugins = false
        if (action.payload) {
          state.allPlugins = action.payload.plugins
        }
      })
      .addCase(fetchAllPlugins.rejected, (state, action) => {
        state.isLoadingPlugins = false
        state.error = action.payload as string
      })

    // Approve plugin
    builder
      .addCase(approvePlugin.fulfilled, (state, action) => {
        const { id } = action.payload
        state.pendingPlugins = state.pendingPlugins.filter(p => p.id !== id)
        // Update plugin status in allPlugins if it exists
        const pluginIndex = state.allPlugins.findIndex(p => p.id === id)
        if (pluginIndex !== -1) {
          state.allPlugins[pluginIndex].status = 'approved'
        }
      })

    // Reject plugin
    builder
      .addCase(rejectPlugin.fulfilled, (state, action) => {
        const { id } = action.payload
        state.pendingPlugins = state.pendingPlugins.filter(p => p.id !== id)
        // Update plugin status in allPlugins if it exists
        const pluginIndex = state.allPlugins.findIndex(p => p.id === id)
        if (pluginIndex !== -1) {
          state.allPlugins[pluginIndex].status = 'rejected'
        }
      })

    // Suspend plugin
    builder
      .addCase(suspendPlugin.fulfilled, (state, action) => {
        const { id } = action.payload
        // Update plugin status in allPlugins
        const pluginIndex = state.allPlugins.findIndex(p => p.id === id)
        if (pluginIndex !== -1) {
          state.allPlugins[pluginIndex].status = 'suspended'
        }
      })

    // Suspend user
    builder
      .addCase(suspendUser.fulfilled, (state, action) => {
        const { id } = action.payload
        // Update user status
        const userIndex = state.users.findIndex(u => u.id === id)
        if (userIndex !== -1) {
          state.users[userIndex].status = 'suspended'
        }
      })

    // Fetch audit logs
    builder
      .addCase(fetchAuditLogs.fulfilled, (state, action) => {
        if (action.payload) {
          state.auditLogs = action.payload.logs
        }
      })

    // Fetch security stats
    builder
      .addCase(fetchSecurityStats.pending, (state) => {
        state.isLoadingSecurity = true
      })
      .addCase(fetchSecurityStats.fulfilled, (state, action) => {
        state.isLoadingSecurity = false
        state.securityStats = action.payload
      })
      .addCase(fetchSecurityStats.rejected, (state, action) => {
        state.isLoadingSecurity = false
        state.error = action.payload as string
      })
  },
})

export const { clearError } = adminSlice.actions

// Selectors
export const selectAdminStats = (state: { admin: AdminState }) => state.admin.stats
export const selectUsers = (state: { admin: AdminState }) => state.admin.users
export const selectPendingPlugins = (state: { admin: AdminState }) => state.admin.pendingPlugins
export const selectAllPlugins = (state: { admin: AdminState }) => state.admin.allPlugins
export const selectAuditLogs = (state: { admin: AdminState }) => state.admin.auditLogs
export const selectSecurityStats = (state: { admin: AdminState }) => state.admin.securityStats
export const selectAdminLoading = (state: { admin: AdminState }) => state.admin.isLoading
export const selectAdminError = (state: { admin: AdminState }) => state.admin.error
